import threading
import socket
import random


class StupidClient( threading.Thread ):
	def __init__( self ):
		threading.Thread.__init__( self );
		self.ttl = random.randint( 10, 1000 )
	def run( self ):
		HOST = '127.0.0.1'
		PORT = 54321
		s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
		try:
			s.connect( ( HOST, PORT ) )
			while self.ttl > 0:
				s.sendall( message )
				data = s.recv( 1024 )
				self.ttl -= 1;
		except socket.error:
			s.close()


#PING
try:
	HOST = '127.0.0.1'
	PORT = 54321
	s = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
	s.connect( ( HOST, PORT ) )
	s.close()
except socket.error:
	print "Server is not reachable"
	quit()
#

N = 10
totalCount = 0
message = "Vivan le femmine, viva il buon vino, sostegno e gloria all'umanita', sostegno e gloria all'umanita'"
try:
	while 1:
		while threading.activeCount() <= N:
			StupidClient().start()
			totalCount += 1
except KeyboardInterrupt:
	print "Interrupt received from keyboard"

print "Generated %d clients" % totalCount
